import * as pinyin from 'pinyin';

import { TempalteModel } from '../../database/types/template.d';
import { FirstLetter, GroupTemplateItem } from './template.d';
import GroupTemplate from './template-group-option';

function isLowerCase(ch: string) {
  return ch >= 'a' && ch <= 'z';
}

class TemplateOption {
  private templateList: TempalteModel[] = [];

  private firstLetterArr: FirstLetter[] = [];

  public groupTemplateByLetter: GroupTemplateItem[] = [];

  constructor(templateList: TempalteModel[], isAttachAll?: boolean) {
    this.templateList = templateList;
    this.getFirstLetterFromTemplate(isAttachAll);
    this.getGroupTemplateByLetter();
    this.sort();
  }

  private getFirstLetterFromTemplate(isAttachAll?: boolean) {
    this.firstLetterArr = this.templateList.map((template) => {
      const templatePinYinFirstLetter = pinyin(template.title, {
        style: pinyin.STYLE_FIRST_LETTER
      })?.[0]?.[0] ?? '';
      let templatePinYinFirstLetterContainEnglish = templatePinYinFirstLetter;

      if (templatePinYinFirstLetter.length !== 1) {
        templatePinYinFirstLetterContainEnglish = templatePinYinFirstLetter?.[0]
          ?? '';
      }

      templatePinYinFirstLetterContainEnglish = templatePinYinFirstLetterContainEnglish.toLowerCase();

      if (isLowerCase(templatePinYinFirstLetterContainEnglish)) {
        return {
          firstLetter: templatePinYinFirstLetterContainEnglish.toLowerCase(),
          uuid: template.uuid,
          title: template.title
        };
      }

      return {
        firstLetter: '其他',
        uuid: template.uuid,
        title: template.title
      };
    });

    if (isAttachAll) {
      this.firstLetterArr.unshift({
        firstLetter: '全部',
        uuid: 'all',
        title: '全部'
      });
    }
  }

  private getGroupTemplateByLetter() {
    const groupTemplateModel = new GroupTemplate();

    this.firstLetterArr.forEach((firstLetter) => {
      groupTemplateModel.addItem(firstLetter);
    });

    this.groupTemplateByLetter = groupTemplateModel.groupTemplate;
  }

  /**
   * 排序，“其他”选项在最后
   */
  private sort() {
    this.groupTemplateByLetter.sort((a, b) => {
      if (a.label === '全部') {
        return -1;
      }

      if (b.label === '全部') {
        return 1;
      }

      if (a.label === '其他') {
        return 1;
      }

      if (b.label === '其他') {
        return -1;
      }

      if (a.label > b.label) {
        return 1;
      }

      if (a.label < b.label) {
        return -1;
      }

      return 0;
    });
  }
}

export default TemplateOption;
